package com.shz.appletsapi.interceptor;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.WebUtils;

import com.shz.appletsapi.common.utils.PwdUtil;

import lombok.extern.slf4j.Slf4j;


/**
 *  加密响应
 * @author zy
 *
 */
@Component
@Slf4j
public class UrlInterceptor implements HandlerInterceptor {

	

	// 访问方法结束
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception e)
			throws Exception {
		// TODO Auto-generated method stub
	
	}

	// 访问方法后加密
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model)
			throws Exception {
		// TODO Auto-generated method stub	
		log.info("interceptor end");
		response.setStatus(HttpStatus.OK.value());
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setDateHeader("Expires", -1);
		response.setHeader("Cache-Control", "no-cache");
		String payload = null;
		ContentCachingResponseWrapper responseWraper = WebUtils.getNativeResponse(response,
				ContentCachingResponseWrapper.class);
		if (responseWraper != null) {
			byte[] buf = responseWraper.getContentAsByteArray();
			if (buf.length > 0) {
				int length = Math.min(buf.length, Integer.MAX_VALUE);
				try {
					payload = new String(buf, 0, length, responseWraper.getCharacterEncoding());
				} catch (UnsupportedEncodingException ex) {
					payload = "[unknown]";
				}
			}
		}
		String objStr =  PwdUtil.encryptString(payload,PwdUtil.PSWD);
		if(!response.isCommitted()) {
			response.resetBuffer();
		}	
		response.getWriter().write(objStr);
		response.getWriter().flush();
		response.getWriter().close(); 
	}

	// 访问方法前解密
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		/*log.info("interceptor start");
		String param = request.getParameter("params");
		if (!StringUtils.isEmpty(param)) {
			log.info("Decryption start");
			String r = new String(PwdUtil.decryptString(param, PwdUtil.PSWD));
			String[] strs = r.split("&");
			for (String str : strs) {
				log.info("str :" + str);
				request.setAttribute(str.substring(0, str.indexOf("=")), str.substring(str.indexOf("=") + 1));
			}
		}*/
		return true;
	}

	public static void main(String[] args) {
		String str = "userId=test";
		System.out.println(str.substring(str.indexOf("=") + 1));
		System.out.println(str.substring(0, str.indexOf("=")));
	}

}
